import request from '../utils/request.js';

// 创建一个不需要认证的请求实例
const requestWithoutAuth = (options) => {
  // 显示加载提示
  if (options.showLoading !== false) {
    uni.showLoading({
      title: options.loadingText || '加载中...'
    });
  }

  // 构造请求配置
  const config = {
    url: options.url,
    method: options.method || 'POST',
    data: options.data || {},
    header: {
      'Content-Type': 'application/json',
      ...options.header
    },
    ...options
  };

  // 打印请求信息，方便调试
  console.log('Request URL:', config.url);
  console.log('Request Method:', config.method);
  console.log('Request Data:', config.data);
  console.log('Request Headers:', config.header);

  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success: (res) => {
        // 隐藏加载提示
        if (options.showLoading !== false) {
          uni.hideLoading();
        }
        
        // 根据状态码处理
        if (res.statusCode === 200) {
          console.log('请求成功:', res.data);
          resolve(res.data);
        } else {
          console.log('请求失败 - 状态码:', res.statusCode, '响应:', res);
          uni.showToast({
            title: res.data?.message || '请求失败',
            icon: 'none'
          });
          reject(res);
        }
      },
      fail: (err) => {
        // 隐藏加载提示
        if (options.showLoading !== false) {
          uni.hideLoading();
        }
        
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        });
        console.error('网络请求失败:', err);
        reject(err);
      }
    });
  });
};

// 获取工单列表
export const getTicketList = (params) => {
  return requestWithoutAuth({
    url: '/api/order/workOrderInfo/queryPageList',
    method: 'POST',
    data: params
  });
};

// 获取工单详情
export const getTicketDetail = (id) => {
  return requestWithoutAuth({
    url: '/api/order/workOrderInfo/get',
    method: 'POST',
    data: { id }
  });
};

// 创建工单
export const createTicket = (data) => {
  // 获取当前用户ID
  let userId = null;
  try {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      const user = JSON.parse(userInfo);
      userId = user.id || user.userId || null;
    }
  } catch (e) {
    console.error('解析用户信息失败:', e);
  }
  
  // 转换前端数据格式为后端需要的格式
  const backendData = {
    title: data.title,
    des: data.description,
    name: data.contact,  // 联系人姓名
    phone: data.contact, // 联系人电话
    address: data.address, // 服务地址
    pic: data.image,     // 图片
    userId: userId       // 用户ID
  };
  
  console.log('提交工单数据:', backendData);
  
  // 使用不需要认证的请求方式
  return requestWithoutAuth({
    url: '/api/order/workOrderInfo/add',
    method: 'POST',
    data: backendData
  });
};

// 更新工单
export const updateTicket = (data) => {
  return requestWithoutAuth({
    url: '/api/order/workOrderInfo/update',
    method: 'POST',
    data
  });
};

// 删除工单
export const deleteTicket = (id) => {
  return requestWithoutAuth({
    url: '/api/order/workOrderInfo/delete',
    method: 'POST',
    data: { id }
  });
};